<template>
	<view class="content">
		<view class="topbar-tabs">
			<view class="left-tabs">
				<u-tabs
					:list="tabsList"
					:is-scroll="false"
					:current="tabsCurrent"
					:show-bar="false"
					inactive-color="#999"
					active-color="#fff"
					:active-item-style="{
						'font-size': '50rpx'
					}"
					font-size="30"
					@change="changeType"
				></u-tabs>
			</view>
			<view class="rg-order" @click="toOrderList"><u-icon name="order" size="38" color="#999"></u-icon></view>
		</view>
		<view class="list-content">
			<view class="tabsborder">
				<u-tabs-swiper
					ref="uTabs"
					:list="changeType ? listBuy : listSell"
					:current="current"
					height="80"
					active-color="#00a2e9"
					inactive-color="#9e9e9e"
					bar-width="70"
					:bold="false"
					bar-height="4"
					gutter="59"
					@change="tabsChange"
				></u-tabs-swiper>
			</view>
			<swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
				<swiper-item class="swiper-item" v-for="(item, index) in !tabsCurrent ? listBuy : listSell" :key="index">
					<scroll-view scroll-y style="height: 100%;width: 100%;" @scrolltolower="onreachBottom">
						<view class="legal-box">
							<template v-if="item.loadStatus !== 'nomore' || item.data.length">
								<block v-for="(info, idx) in item.data" :key="idx">
									<legal-item
										:name="info.user.user_name"
										:token-type="'USDT'"
										:number="info.ofSQShenyuJiner"
										:limits="'1.00-' + (info.ofSQShenyuJiner * info.ofPrice).toFixed(2)"
										:volume="info.ofUJiner - info.ofSQShenyuJiner"
										:price="info.ofPrice"
										cond :cancel="info.ofUid == userInfo.id"
										:payment="[]"
										:type="tabsCurrent"
										@click="info.ofUid == userInfo.id ? toCancel(info.ofId) : toNext(tabsCurrent, info.ofId, 'USDT', [], info.ofPrice)"
										@handle="info.ofUid == userInfo.id ? toCancel(info.ofId) : toNext(tabsCurrent, info.ofId, 'USDT', [], info.ofPrice)"
									></legal-item>
								</block>
								<view class="loading"><u-loadmore :status="item.loadStatus" /></view>
							</template>
							<template v-else>
								<view class="no-data"><u-empty text="没有数据哦~" mode="search"></u-empty></view>
							</template>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		<!-- fixed button -->
		<view class="fixed-btn" @click="toAddOrder"><u-icon name="plus" size="32" color="#00a2e9"></u-icon></view>
	</view>
</template>

<script>
  import {
  	CUser
  } from '@/common/cache/user.js'
  var cache_user = new CUser();
export default {
	data() {
		return {
			tabsList: [{ name: '我要买' }, { name: '我要卖' }],
			tabsCurrent: 0,
			listBuy: [
				{
					name: 'USDT',
					data: [],
					loadStatus: 'loadmore',
					page: 1
				}
			],
			listSell: [
				{
					name: 'USDT',
					data: [],
					loadStatus: 'loadmore',
					page: 1
				}
			],
			pageSize: 20, // 设置默认加载数量
			current: 0,
			swiperCurrent: 0,
      userInfo: {}
		};
	},
  onShow() {
    cache_user.userinfo().then((res) => {
      this.userInfo = res
    })
    this.onreachBottom('init')
  },
	methods: {
    // 取消订单
    toCancel (id) {
      uni.showModal({
        title: '提示',
        content: '是否确认取消该委托单?',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading()
            this.$api.http
            .post('assistance/CurrencyTransaction/cancelOrder', {
              id: id
            }).then((res) => {
              uni.hideLoading()
              this.$api.msg(res.msg)
              if (res.status == 200) {
                this.onreachBottom('init')
              }
            })
          } else {
            
          }
        }
      })
    },
		toOrderList() {
			uni.navigateTo({
				url: './orderList'
			});
		},
		/**
		 * 购买 or 出售
		 */
		toNext(type, id, tokenType, payment, price) {
      uni.navigateTo({
        url: `./purchase?type=${1-type}&id=${id}&tokenType=${tokenType}&payment=${payment}&price=${price}`
      });
		},
		toAddOrder() {
			let type = !this.tabsCurrent ? this.listBuy[this.current].name : this.listSell[this.current].name;
			uni.navigateTo({
				url: `./addOrder?type=${type}`
			});
		},
		changeType(index) {
			this.tabsCurrent = index;
			setTimeout(() => {
        this.onreachBottom('init');
      }, 0)
		},
		// tabs通知swiper切换
		tabsChange(index) {
			this.swiperCurrent = index;
		},
		// swiper-item左右移动，通知tabs的滑块跟随移动
		transition(e) {
			let dx = e.detail.dx;
			this.$refs.uTabs.setDx(dx);
		},
		// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
		// swiper滑动结束，分别设置tabs和swiper的状态
		animationfinish(e) {
			let current = e.detail.current;
			this.$refs.uTabs.setFinishCurrent(current);
			this.swiperCurrent = current;
			if (this.current !== current) {
				this.current = current;
				this.onreachBottom();
			}
		},
		// scroll-view到底部加载更多
		onreachBottom(type) {
			let item = !this.tabsCurrent ? this.listBuy[this.current] : this.listSell[this.current];
			if (item.loadStatus == 'loadmore' || type == 'init') {
				item.loadStatus = 'loading';
				// 请求数据
				this.getList(type).then(({ data }) => {
					item.page++;
          if (type == 'init') {
            item.data = data;
          } else {
            item.data = item.data.concat(data);
          }
					item.loadStatus = data.length == this.pageSize ? 'loadmore' : 'nomore';
				});
			}
		},
		/**
		 * 获取列表
		 */
		getList(type) {
			let page = !this.tabsCurrent ? this.listBuy[this.current].page : this.listSell[this.current].page;
      if (type == 'init') page = 1;
			return new Promise(resolve => {
        console.log(page)
        this.$api.http.
        get(`assistance/CurrencyTransaction/wantInvestLists?page=${page}&type=${2-this.tabsCurrent}&orderfield=ofId&order=desc`)
        .then(res => {
          resolve(res)
        })
			});
		}
	}
};
</script>

<style lang="scss">
page {
	height: 100%;
}
.content {
	height: 100%;
}
.list-content {
	height: calc(100% - 160rpx);
}
.topbar-tabs {
	background-color: $bg-theme;
	padding-top: 80rpx;
	display: flex;
	align-items: center;
	.left-tabs {
		width: 400rpx;
		padding-left: 20rpx;
	}
	.rg-order {
		margin-left: auto;
		padding: 10rpx 25rpx 0;
	}
}
.tabsborder {
	padding-left: 10rpx;
	height: 80rpx;
}
.swiper {
	border-top: 1rpx solid $uni-text-color-grey;
	height: calc(100% - 80rpx);
}
.loading {
	padding: 16rpx 0;
}
.no-data {
	padding-top: 100rpx;
}
.fixed-btn {
	position: fixed;
	right: 32rpx;
	bottom: 132rpx;
	border-radius: 50%;
	box-shadow: 4rpx 4rpx 24rpx rgba($color: #000000, $alpha: 0.1);
	background-color: #fff;
	border: 1rpx solid $uni-text-color-grey;
	width: 92rpx;
	height: 92rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 111;
	&:active {
		background-color: #eee;
	}
}
</style>
